/**
 * Copyright(c) 2015 Jade Techonologies Co., Ltd.
 *
 * History:
 *   15-1-8 下午4:10 Created by lyyang
 */
package com.jade.framework.security.shiro.authc;

import com.jade.framework.base.util.encryption.Encryption;
import com.jade.framework.base.util.encryption.EncryptionUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

/**
 * 系统默认加密匹配器,用于shiro的realm认证匹配
 *
 * @author <a href="mailto:lyyang@jade.com">lyyang</a>
 * @version 1.0 15-1-8 下午4:10
 */
public class DefaultEncryptMatcher
        implements CredentialsMatcher
{
    protected Encryption encryption = EncryptionUtils.getDefaultEncryption();

    public void setEncryption(String name)
    {
        this.encryption = EncryptionUtils.getEncryption(name);
    }

    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo)
    {
        String sysPassword = String.valueOf(authenticationInfo.getCredentials());
        String password = null;
        Object credentials = authenticationToken.getCredentials();
        if (credentials instanceof char[]) {
            password = new String((char[]) credentials);
        }
        else {
            password = (String) credentials;
        }
        if (encryption != null) {
            return encryption.check(password, sysPassword);
        }
        return sysPassword.equals(password);
    }
}
